package com.heima.search.service.impl;

import com.heima.common.exception.CustomException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.search.dtos.UserSearchDto;
import com.heima.search.pojos.ApAssociateWords;
import com.heima.search.service.AssociateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AssociateServiceImpl implements AssociateService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 用户搜索-关键词联想
     *
     * @param userSearchDto 用户搜索的关键字
     * @return 返回结果列表
     */
    @Override
    public List<ApAssociateWords> search(UserSearchDto userSearchDto) {
        //参数校验
        if (userSearchDto == null || userSearchDto.getSearchWords() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Query query = Query.query(
                        Criteria
                                .where("associateWords")
                                .regex(".*?\\" + userSearchDto.getSearchWords() + ".*"))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(10);//查询10条
        List<ApAssociateWords> associateWords = mongoTemplate.find(query, ApAssociateWords.class);
        return associateWords;
    }
}
